<template>
  <el-dialog v-model="dialogVisible" title="相关门店" width="50%" @close="handleClose" >
    <div class="mb-4">
      <el-alert
        :title="`数据统计：共 ${props.storeList.length} 条数据`"
        type="info"
        :closable="false"
      />
    </div>
    <el-table :data="showStoreList" style="width: 100%" border>
      <el-table-column prop="name" label="门店名称" align="center" />
      <el-table-column prop="agentName" label="关联代理" align="center" />
      <el-table-column prop="detailAddress" label="门店归属" align="center" />
      <el-table-column label="开店时间" align="center">
        <template #default="scope">
          <span>{{ formateDateday(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="action" label="操作" align="center" width="150">
        <template #default="scope">
          <div class="flex gap-2">
            <el-button type="primary" link @click="handleView(scope.row)">查看</el-button>
            <el-dropdown trigger="hover" @command="(cmd) => handleCommand(cmd, scope.row)" @visible-change="forceUpdate">
              <span class="el-dropdown-link">
                {{ scope.row.currentLabel }}
                <el-icon class="el-icon--right">
                  <arrow-down />
                </el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="0">区域内</el-dropdown-item>
                  <el-dropdown-item 
                    command="1" 
                    :disabled=" scope.row.haBindMasterStore "
                  >
                    直属
                  </el-dropdown-item>
                  <el-dropdown-item command="2">总部直属</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <div class="flex justify-end">
         <el-button   @click="handleClose">关闭</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watchEffect, computed, onMounted } from 'vue'
import { ArrowDown } from '@element-plus/icons-vue'
import { formateDateday } from '@/utils/formatTime'
import { useRouter } from 'vue-router'
import { bindAgentUsersStoreRelation } from '@/api/mall/agent/index'
import { ElMessage } from 'element-plus'

// 定义组件名，便于keep-alive识别
defineOptions({ name: 'RelatedStores' })

const router = useRouter()

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  storeList: {
    type: Array,
    default: () => []
  },
  agentId: {
    type: Number,
    default: 0
  }
})

const emits = defineEmits(['update:modelValue', 'update:storeList'])
const dialogVisible = ref(false)
// 创建内部状态来管理门店列表
const internalStoreList = ref([...props.storeList])

// 监听props变化，更新内部状态
watchEffect(() => {
  internalStoreList.value = [...props.storeList]
})

const handleClose = () => {
  emits('update:modelValue', false)
}
const showStoreList = computed(() => {
  return internalStoreList.value.map((item:any) => {
    // 确保每次重新计算时都返回一个新对象
    return {
      ...item,
      currentLabel: item.relationType === 0 ? '区域内' : item.relationType === 1 ? '直属' : item.relationType === 2 ? '总部直属' : '区域内'
    }
  })
})

// 检查是否已有直属门店
// const hasDirectStore = computed(() => {
//   // 检查是否有任何一行是直属状态
//   return internalStoreList.value.some((item: any) => item.relationType === 1)
// })

watchEffect(() => {
  dialogVisible.value = props.modelValue
})
const handleCommand = async (command: string, row: any) => {
  // 记录之前的状态
  const previousRelationType = row.relationType
  
  // 如果选择直属，先检查是否已有其他直属门店
  // if (command === '1') {
  //   // 如果当前行已经是直属，不做任何操作
  //   if (row.relationType === 1) {
  //     return
  //   }
    
  //   // 如果已有直属门店，提示用户
  //   if (hasDirectStore.value) {
  //     ElMessage.warning('只能设置一个直属门店')
  //     return
  //   }
  // }
  
  // 确定新的标签文本
  let newLabel = '区域内'
  switch (command) {
    case '0':
      newLabel = '区域内'
      break
    case '1':
      newLabel = '直属'
      break
    case '2':
      newLabel = '总部直属'
      break
  }
  
  // 更新行的relationType
  const index = internalStoreList.value.findIndex((item: any) => item.id === row.id)
  if (index !== -1) {
    // 创建新对象以确保Vue能检测到变化
    const updatedItem = { 
      ...internalStoreList.value[index] as Record<string, any>, 
      relationType: Number(command),
      currentLabel: newLabel
    }
    // 替换数组中的项
    internalStoreList.value.splice(index, 1, updatedItem)
    // 强制更新整个数组
    internalStoreList.value = [...internalStoreList.value]
  }
  
  // 更新父组件的storeList
  emits('update:storeList', internalStoreList.value)
}
const handleView = (row: any) => {
  console.log(row)
  // mall/store/pick-up-store
  router.push({
    path: '/mall/store/pick-up-store'
  })
}
const handleSave = async () => {
  await bindAgentUsersStoreRelation({
    agentId: props.agentId,
    storeRelationList: internalStoreList.value.map((item:any) => {
      return {
        storeId: item.id,
        relationType: item.relationType
      }
    })
  })
  ElMessage.success('保存成功')
  handleClose()
}

// 强制更新组件，确保下拉菜单状态是最新的
const forceUpdate = (visible: boolean) => {
  if (visible) {
    // 下拉菜单打开时，强制更新内部状态
    internalStoreList.value = [...internalStoreList.value]
  }
}
</script>

<style scoped lang="scss">
.el-dropdown-link {
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 4px;
}
</style>